import random
import time
import base64
from time import sleep

import ddddocr
import requests
from DrissionPage import Chromium, ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage
from 华为自动登入 import dddd_test, slide_test

from slider_test import recognize_slider_distance  # 上文已详细讲解

# 创建浏览器实例
co = ChromiumOptions().set_browser_path(r'C:\Path\To\chrome.exe')
tab = Chromium().latest_tab

def base64_decode(data):
    return base64.b64decode(data + '==')

# 656
def login_with_slider():
    try:
        # 初始化浏览器
        page = ChromiumPage()
        # 启动网络监听
        page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
        # 访问登录页面
        page.get(
            'https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a4bf7000001d17496045915977400%26h%3D1749604591.5980%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc1721fefb9cebd72e7ff228bf7bad87911c5c8b17c32cc022980dc744bb3eb1f&validated=true')
        # 输入账号密码
        page.ele('.hwid-input userAccount').input('business_m@igame58.com')
        sleep(1)
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        time.sleep(2)
        # 1. 获取滑块图片元素
        target_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[2]')
        bg_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[1]')
        if not target_element or not bg_element:
            print("未找到滑块图片元素")
            return False, None
        # 2. 获取图片URL
        target_src = target_element.attr('src')
        bg_src = bg_element.attr('src')


        # # 4. 获取滑块和背景图片
        slide = ddddocr.DdddOcr(det=False, ocr=False)
        background_bytes = requests.get(bg_src, timeout=10).content
        target_bytes = requests.get(target_src, timeout=10).content
        res = slide.slide_match(target_bytes, background_bytes)

        raw_distance = res['target'][0]
        # 2. 精确计算
        scale_factor = 260 / 320  # 显示宽度/原始宽度
        calibrated_distance = raw_distance * scale_factor
        # 3. 动态补偿（小图居中补偿）
        small_img_width = 49  # 小图显示宽度
        compensated_distance = calibrated_distance - (small_img_width / 2)  + 25 # +3px经验值
        target_length = compensated_distance

        print(f"识别距离为：{res}")
        print(f"需要滑动的距离: {target_length}px")

        slide_btn = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')

        if not slide_btn:
            print("未找到滑块按钮")
            return False, None

        (page.actions.move_to(slide_btn)
         .wait(0.2)
         .m_hold(slide_btn)
         .wait(0.3)
         .move(target_length, 0, 0.8)
         .m_release())
        print(f"滑动的距离为: {target_length}px")

        # 5. 等待验证完成
        time.sleep(5)  # 等待验证结果

        # 6. 检查最新请求头
        try:
            latest_request = page.listen.wait()
            headers = latest_request.request.extra_info.headers
            cookies = headers.get('Cookie', '') if headers else ''

            if cookies:
                print("成功获取到请求头，包含Cookie:", cookies[:50] + "...")
                # 转换为可序列化的字典
                serializable_headers = dict(headers)  # 确保headers是普通字典
                return {
                    "advertiserId": "1377601253676167168",
                    "headers": serializable_headers
                }
            else:
                print("获取到请求头但不包含Cookie")
                return {
                    "success": False,
                    "message": "获取到请求头但不包含Cookie"
                }

        except Exception as e:
            print(f"获取请求头失败: {str(e)}")
            return {
                "success": False,
                "message": f"获取请求头失败: {str(e)}"
            }

    except Exception as e:
            print(f"登录失败，错误信息：{e}")
            return {
                "success": False,
                "message": f"登录失败: {str(e)}"
            }

#168
def login_with_slider168():
    try:
        # 初始化浏览器
        page = ChromiumPage()
        # 启动网络监听
        page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
        # 访问登录页面
        page.get(
            'https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a4bf7000001d17496045915977400%26h%3D1749604591.5980%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc1721fefb9cebd72e7ff228bf7bad87911c5c8b17c32cc022980dc744bb3eb1f&validated=true')
        # 输入账号密码
        page.ele('.hwid-input userAccount').input('13715176464')
        sleep(1)
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        time.sleep(2)
        # 1. 获取滑块图片元素
        target_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[2]')
        bg_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[1]')
        if not target_element or not bg_element:
            print("未找到滑块图片元素")
            return False, None
        # 2. 获取图片URL
        target_src = target_element.attr('src')
        bg_src = bg_element.attr('src')


        # # 4. 获取滑块和背景图片
        slide = ddddocr.DdddOcr(det=False, ocr=False)
        background_bytes = requests.get(bg_src, timeout=10).content
        target_bytes = requests.get(target_src, timeout=10).content
        res = slide.slide_match(target_bytes, background_bytes)

        raw_distance = res['target'][0]
        # 2. 精确计算
        scale_factor = 260 / 320  # 显示宽度/原始宽度
        calibrated_distance = raw_distance * scale_factor
        # 3. 动态补偿（小图居中补偿）
        small_img_width = 49  # 小图显示宽度
        compensated_distance = calibrated_distance - (small_img_width / 2)  + 25 # +3px经验值
        target_length = compensated_distance

        print(f"识别距离为：{res}")
        print(f"需要滑动的距离: {target_length}px")

        slide_btn = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')

        if not slide_btn:
            print("未找到滑块按钮")
            return False, None

        (page.actions.move_to(slide_btn)
         .wait(0.2)
         .m_hold(slide_btn)
         .wait(0.3)
         .move(target_length, 0, 0.8)
         .m_release())
        print(f"滑动的距离为: {target_length}px")

        # 5. 等待验证完成
        time.sleep(5)  # 等待验证结果

        # 6. 检查最新请求头
        try:
            latest_request = page.listen.wait()
            headers = latest_request.request.extra_info.headers
            cookies = headers.get('Cookie', '') if headers else ''

            if cookies:
                print("成功获取到请求头，包含Cookie:", cookies[:50] + "...")
                # 转换为可序列化的字典
                serializable_headers = dict(headers)  # 确保headers是普通字典
                return {
                    "advertiserId": "1377601253676167168",
                    "headers": serializable_headers
                }
            else:
                print("获取到请求头但不包含Cookie")
                return {
                    "success": False,
                    "message": "获取到请求头但不包含Cookie"
                }

        except Exception as e:
            print(f"获取请求头失败: {str(e)}")
            return {
                "success": False,
                "message": f"获取请求头失败: {str(e)}"
            }

    except Exception as e:
            print(f"登录失败，错误信息：{e}")
            return {
                "success": False,
                "message": f"登录失败: {str(e)}"
            }


def get_accounts_headers():
    results = []
    accounts = [
        {"advertiserId":"1318796917290838656","username": "business_m@igame58.com", "password": "LEYOU123"},
        {"advertiserId":"1377601253676167168","username": "13715176464", "password": "LEYOU123"}
    ]

    for account in accounts:
        try:
            # 初始化浏览器
            page = ChromiumPage()
            # 启动网络监听
            page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')

            # 访问登录页面
            page.get(
                'https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a4bf7000001d17496045915977400%26h%3D1749604591.5980%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc1721fefb9cebd72e7ff228bf7bad87911c5c8b17c32cc022980dc744bb3eb1f&validated=true')

            # 输入账号密码
            page.ele('.hwid-input userAccount').input(account["username"])
            sleep(1)
            page.ele('.hwid-input hwid-input-pwd').input(account["password"])

            # 点击登录按钮
            login_btn = page.ele('.normalBtn', timeout=10)
            login_btn.click()
            time.sleep(2)

            # 滑块验证部分
            target_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[2]')
            bg_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[1]')
            if not target_element or not bg_element:
                print(f"账号 {account['username']} 未找到滑块图片元素")
                results.append({
                    "username": account["username"],
                    "success": False,
                    "message": "未找到滑块图片元素"
                })
                continue

            # 获取图片URL
            target_src = target_element.attr('src')
            bg_src = bg_element.attr('src')

            # 滑块识别和滑动
            slide = ddddocr.DdddOcr(det=False, ocr=False)
            background_bytes = requests.get(bg_src, timeout=10).content
            target_bytes = requests.get(target_src, timeout=10).content
            res = slide.slide_match(target_bytes, background_bytes)

            raw_distance = res['target'][0]
            scale_factor = 260 / 320
            calibrated_distance = raw_distance * scale_factor
            small_img_width = 49
            compensated_distance = calibrated_distance - (small_img_width / 2) + 25
            target_length = compensated_distance

            slide_btn = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')
            if not slide_btn:
                print(f"账号 {account['username']} 未找到滑块按钮")
                results.append({
                    "username": account["username"],
                    "success": False,
                    "message": "未找到滑块按钮"
                })
                continue

            (page.actions.move_to(slide_btn)
             .wait(0.2)
             .m_hold(slide_btn)
             .wait(0.3)
             .move(target_length, 0, 0.8)
             .m_release())

            # 等待验证完成
            time.sleep(5)

            # 获取请求头
            try:
                latest_request = page.listen.wait()
                headers = latest_request.request.extra_info.headers
                cookies = headers.get('Cookie', '') if headers else ''

                if cookies:
                    print(f"账号 {account['username']} 成功获取到请求头")
                    results.append({
                        "advertiserId": account["advertiserId"],
                        "success": True,
                        "cookies": cookies,
                        "headers": dict(headers)
                    })
                else:
                    print(f"账号 {account['username']} 获取到请求头但不包含Cookie")
                    results.append({
                        "advertiserId": account["advertiserId"],
                        "success": False,
                        "message": "获取到请求头但不包含Cookie"
                    })

            except Exception as e:
                print(f"账号 {account['username']} 获取请求头失败: {str(e)}")
                results.append({
                    "advertiserId": account["advertiserId"],
                    "success": False,
                    "message": f"获取请求头失败: {str(e)}"
                })

            # 关闭当前页面
            page.close()

        except Exception as e:
            print(f"账号 {account['username']} 登录失败，错误信息：{e}")
            results.append({
                "advertiserId": account["advertiserId"],
                "success": False,
                "message": f"登录失败: {str(e)}"
            })
            if 'page' in locals():
                page.close()

    # 返回所有账号的登录结果
    return {
        "success": all(result["success"] for result in results),
        "results": results
    }